package com.wl.dzt.sys.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description 集合工具
 */
public class CollectionUtil {

    /**
     * 类似js中join方法
     * 把一个集合对象中的所有元素根据指定符号连接起来成为字符串
     *
     * @param collection
     * @param delimiter
     * @return
     */
    public static String join(Collection<?> collection, String delimiter) {
        if (collection == null || collection.isEmpty()) {
            return "";
        }

        StringBuilder builder = new StringBuilder();
        collection.forEach(obj -> builder.append(obj + delimiter));
        int last = builder.lastIndexOf(delimiter);
        return builder.delete(last, builder.length()).toString();
    }

    /**
     * 把一个集合中根据指定的字段把这些字段的值通过指定的符号关联起来
     *
     * @param collection
     * @param field
     * @param delimiter
     * @return
     */
    public static String joinByFiled(Collection<?> collection, String field, String delimiter) {
        List<Object> list = new ArrayList<>();
        collection.forEach(obj -> list.add(FieldUtil.doGetMethod(obj, field)));
        return join(list, delimiter);
    }

    /**
     * 获取某个集合中一个字段成为新的集合
     *
     * @param collection
     * @param field
     * @param <T>
     * @return
     */
    public static <T> List<?> getCollectionField(Collection<?> collection, String field) {
        List<T> list = new ArrayList<>();
        collection.forEach(obj -> list.add((T) FieldUtil.doGetMethod(obj, field)));
        return list;
    }

}
